<template>
  <div v-loading="loading" :element-loading-text="loadingText" class="config-edit">
    <div v-show="!showPicDetail">
      <div class="bread-box but20">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">卫浴配置</el-breadcrumb-item>
          <el-breadcrumb-item>卫浴配置单</el-breadcrumb-item>
        </el-breadcrumb>
        <div>
          <el-button size="mini" @click="handleBack">取消</el-button>
          <el-button type="primary" size="mini" @click="handleSave">保存</el-button>
          <el-button type="primary" size="mini" @click="handleSave('C')">提交</el-button>
        </div>
      </div>
      <c-list :column="3">
        <c-list-item label="产品配置单" :value="formData.configCode" />
        <c-list-item label="对应产品配置任务" :value="formData.configTaskCode" />
        <c-list-item label="任务来源" dict-type-code="PRODUCT_CONFIG_TASK_SOURCE" :value="formData.source" />
        <c-list-item label="产品配置类型" dict-type-code="PRO_CONFIG_TYPE" :value="formData.proConfigType" />
        <c-list-item label="产品配置进度" dict-type-code="PRO_CONFIG_SCHEDULE" :value="formData.schedule" />
        <c-list-item label="是否含自主配置" dict-type-code="BOOLEANS" :value="formData.isLibertyLoad" />
        <c-list-item label="门店建设项目号" :value="formData.constCode" />
        <c-list-item label="所属门店编码" :value="formData.shopCode" />
        <c-list-item label="所属门店名称" :value="formData.shopName" />
        <c-list-item label="所属客户编码" :value="formData.clientCode" />
        <c-list-item label="所属客户名称" :value="formData.clientName" />
        <c-list-item label="所属办事处" :value="formData.officeName" />
        <c-list-item label="产品配置人员" :value="formData.proConfiguratorName" />
        <c-list-item label="创建人" :value="formData.createBy" />
        <c-list-item label="创建时间" :value="formData.createTime" />
        <c-list-item label="修改人" :value="formData.lastUpdateBy" />
        <c-list-item label="修改时间" :value="formData.lastUpdateTime" />
      </c-list>
      <c-section title="关联图纸信息">
        <c-table-box hide-func table-max-height="400" :data="formData.designPictureDtos" :table-config="picTableConfig" />
      </c-section>
      <c-section title="产品出配置清单">
        <div class="btn-container">
          <el-button type="primary" @click="addProduct">新增产品</el-button>
          <el-button type="primary" @click="addModel">新增型号</el-button>
          <el-button type="primary" @click="delProduct">删除</el-button>
        <!-- <el-button type="primary">导入</el-button> -->
        <!-- <el-button type="primary">导出</el-button> -->
        </div>
        <AddProduct v-if="showProductDlg" ref="productDlg" :visible.sync="showProductDlg" :detail-data="checkProData" @success="getProductData" />
        <AddModel v-if="showMatchDlg" ref="modelDlg" :visible.sync="showMatchDlg" :detail-data="checkModelData" @success="getModelData" />
        <!-- <c-table-box index :data="proConfigTableData" :table-config="tableConfig" /> -->
        <el-table
          ref="refTable"
          v-loading="tableLoading"
          element-loading-text="加载中"
          :data="proConfigTableData"
          border
          highlight-current-row
          :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
          style="width: 100%; margin-top: 20px; margin-bottom: 20px"
          @selection-change="selectionChangeHandle"
        >
          <el-table-column v-if="flag !== 'detail'" type="selection" width="55" />
          <el-table-column prop="productCode" label="产品编码" min-width="80" show-overflow-tooltip />
          <el-table-column prop="productDesc" label="产品描述" min-width="100" show-overflow-tooltip />
          <el-table-column prop="modelName" label="型号" min-width="100" show-overflow-tooltip>
            <template slot="header">
              <span style="color: red">*</span>型号
            </template>
          </el-table-column>
          <el-table-column prop="seriesName" label="系列" min-width="100" show-overflow-tooltip />
          <el-table-column prop="categoryName" label="所属品类" min-width="100">
            <template slot="header">
              <span style="color: red">*</span>所属品类
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.productCode">{{ scope.row.categoryName }}</span>
              <input-with-dialog
                v-else
                v-model="scope.row.category"
                :props="{label:'name',value:'code'}"
                :config="categoryConfig"
                @change="categoryChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="productNumber" label="数量" min-width="100">
            <template slot="header">
              <span style="color: red">*</span>数量
            </template>
            <template slot-scope="scope">
              <!-- <span v-if="scope.row.productCode">{{ scope.row.returnNum }}</span> -->
              <el-input v-model="scope.row.productNumber" type="number" size="mini" placeholder="请输入数量" min="1" :max="scope.row.quantity" @blur="handelBlur(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="productState" label="产品状态" min-width="100">
            <template slot-scope="scope">
              <span>{{ formaterData(proStateList, scope.row.productState) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="pcontrolState" label="采购控制状态" min-width="100">
            <template slot-scope="scope">
              <span>{{ formaterData(canBePurchaseList, scope.row.pcontrolState) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="placeOrderType" label="产品下单类型" min-width="100">
            <template slot="header">
              <span style="color: red">*</span>产品下单类型
            </template>
            <template slot-scope="scope">
              <span v-if="scope.row.productCode">{{ formaterData(placeOrderTypeList, scope.row.placeOrderType) }}</span>
              <!-- <c-dict-select v-else v-model="formData.placeOrderType" dict-type-code="PLACE_ORDER_TYPE" placeholder="产品下单类型" /> -->
              <el-select v-else v-model="scope.row.placeOrderType" size="mini" placeholder="请选择产品下单类型" style="width:100%">
                <el-option v-for="item in modelorderTypeList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="placeOrderDesc" label="下单说明" min-width="100">
            <template slot-scope="scope">
              <!-- <span v-if="flag === 'detail'">{{ formaterArr(scope.row.placeOrderDesc) }}</span> -->
              <el-input v-model="scope.row.placeOrderDesc" placeholder="请输入下单说明" maxlength="128" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </c-section>
    </div>
    <detail v-if="showPicDetail" :shop-config-data="rowId" page-flag="shopConfig" :page-show.sync="showPicDetail" @goBack="backDetail" />
    <!-- <div class="btn-container">
      <el-button type="primary">取消</el-button>
      <el-button type="primary">保存</el-button>
      <el-button type="primary">提交</el-button>
    </div> -->
  </div>
</template>
<script>
// import RelevanceDrawing from '../../components/relevanceDrawing'
import AddProduct from './components/addProduct'
import AddModel from './components/addModel'
import detail from '../../../shopDrawing/management/detail.vue'
import { getDictByTypeCode, getProConfigEditData, saveProConfigEditData } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'
import { getAreaData } from '../../task/components/index'
export default {
  name: 'PCBathroomConfigEdit',
  components: {
    // RelevanceDrawing,
    AddProduct,
    AddModel, detail
  },
  props: {
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      rowId: '',
      showPicDetail: false,
      loading: false,
      loadingText: '',
      areaList: [],
      modelorderTypeList: [],
      placeOrderTypeList: [],
      selectedRows: [],
      showProductDlg: false,
      showMatchDlg: false,
      activedData: {},
      formData: {
        designPictureDtos: []
      },
      // 品类弹窗
      categoryConfig: {
        title: '品类',
        interfacePath: `/select-service/api/v1/productCategory/page`,
        // apiHeader: { 'Distributor': getDisCode() },
        setting: [
          {
            prop: 'code',
            title: '编码'
          },
          {
            prop: 'name',
            title: '名称'
          }
        ]
      },
      outpicCategoryData: [],
      otherFilters: [],
      picTableConfig: {
        setting: [
          {
            prop: 'picTaskCode',
            label: '图纸编码',
            minWidth: 100,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toPicDetail
          },
          {
            prop: 'picType',
            label: '图纸类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_TYPE'
            },
            minWidth: 100
          },
          {
            prop: 'designRange',
            label: '设计范围',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designRange) {
                return
              }
              let list = []
              if (typeof (row.designRange) === 'string') {
                list = row.designRange.split(',')
              } else {
                list = row.designRange
              }
              const arr = []
              this.designRangeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'decorationType',
            label: '装修形式',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.decorationType) {
                return
              }
              let list = []
              if (typeof (row.decorationType) === 'string') {
                list = row.decorationType.split(',')
              } else {
                list = row.decorationType
              }
              const arr = []
              this.decorationTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designSpace',
            label: '设计区域',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designSpace) {
                return
              }
              let list = []
              if (typeof (row.designSpace) === 'string') {
                list = row.designSpace.split(',')
              } else {
                list = row.designSpace
              }
              const arr = []
              this.areaList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designBizType',
            label: '设计业务类型',
            minWidth: 140,
            render: (creat, row) => {
              if (!row.designBizType) {
                return
              }
              let list = []
              if (typeof (row.designBizType) === 'string') {
                list = row.designBizType.split(',')
              } else {
                list = row.designBizType
              }
              const arr = []
              this.designBizTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'picTotalArea',
            label: '设计总面积',
            minWidth: 120
          },
          // {
          //   prop: 'finishedProductAreaSummary',
          //   label: '成品业务面积汇总',
          //   minWidth: 100
          // },
          {
            prop: 'softwareSumArea',
            label: '软体区面积',
            minWidth: 120
          },
          {
            prop: 'suiteSumArea',
            label: '套房区面积',
            minWidth: 120
          },
          {
            prop: 'haveEAndC',
            label: '是否含成融定',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: 140
          },
          {
            prop: 'eandCArea',
            label: '成融定面积',
            minWidth: 120
          },
          {
            prop: 'newBusinessAreaSummary',
            label: '新业务面积汇总',
            minWidth: 100
          },
          {
            prop: 'expectEndTime',
            label: '预计设计完成时间',
            minWidth: 140
          },
          {
            prop: 'designUnitName',
            label: '设计单位',
            minWidth: 100
          },
          {
            prop: 'designerName',
            label: '设计师',
            minWidth: 100
          },
          {
            prop: 'schedule',
            label: '图纸进度',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_SCHEDULE'
            },
            minWidth: 100
          },
          {
            prop: 'state',
            label: '图纸状态',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_STATE'
            },
            minWidth: 100
          }
        ]
      },
      proConfigTableData: [],
      designRangeList: [],
      decorationTypeList: [],
      designSpaceList: [],
      designBizTypeList: [],
      proStateList: [],
      canBePurchaseList: [],
      checkModelData: {},
      checkProData: {}
    }
  },
  async created() {
    this.loading = true
    this.loadingText = '加载中'
    await this.getDictByPatchTypeAll(['PRODUCT_STATE', 'CAN_BE_PURCHASE']).then(res => {
      this.proStateList = res.PRODUCT_STATE
      this.canBePurchaseList = res.CAN_BE_PURCHASE
    })
    await this.getDictByTypeCode(['PLACE_ORDER_TYPE', 'DECORATION_RANGE',
      'DECORATION_FORM', 'BELONG_REGION', 'BIZ_TYPE']).then(res => {
      this.placeOrderTypeList = res.PLACE_ORDER_TYPE
      this.modelorderTypeList = this.placeOrderTypeList.filter(item => item.dictCode !== 'C')
      this.designRangeList = res.DECORATION_RANGE // 设计范围
      this.decorationTypeList = res.DECORATION_FORM // 装修形式
      this.designSpaceList = res.BELONG_REGION // 设计区域
      this.designBizTypeList = res.BIZ_TYPE // 设计业务类型
    })
    this.areaList = await getAreaData()
    getProConfigEditData(this.$route.params.id).then(res => {
      if (res.success && res.data) {
        this.formData = res.data
        if (res.data.configOutPicDtos) {
          this.proConfigTableData = res.data.configOutPicDtos[0].configDetailDtos
          this.proConfigTableData.forEach(item => {
            if (!item.productCode) {
              const category = [{ label: item.categoryName, value: item.categoryCode }]
              this.$set(item, 'category', category)
            }
          })
        }
      }
      this.loading = false
    }).catch(() => {
      this.loading = false
    })
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByTypeCode(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 获取数据字典
    async getDictByTypeCode(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr || !arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 新增产品
    addProduct() {
      if (this.proConfigTableData.length) {
        this.checkProData.otherFilters = this.proConfigTableData.filter(item => item.productCode && item.productCode.length)
      }
      this.showProductDlg = true
    },
    // 新增型号
    addModel() {
      if (this.proConfigTableData.length) {
        this.checkModelData.otherFilters = this.proConfigTableData
      }
      this.showMatchDlg = true
    },
    // 获取产品
    getProductData(data) {
      if (!this.proConfigTableData.length) {
        const dataArr = data.map(item => {
          const obj = {
            productCode: item.productCode,
            productDesc: item.productName,
            modelCode: item.prodModelCode,
            modelName: item.prodModelName,
            categoryName: item.productCategoryName,
            categoryCode: item.productCategoryCode,
            seriesName: item.saleSeriesName,
            seriesCode: item.saleSeriesCode,
            productState: item.proState,
            pcontrolState: item.canBePurchase,
            productNumber: 1,
            placeOrderType: 'C',
            placeOrderDesc: ''
          }
          return obj
        })
        this.proConfigTableData = [...this.proConfigTableData, ...dataArr]
        return
      }
      const arr1 = []
      const arr2 = []
      data.forEach(item => {
        const flag = this.proConfigTableData.some(v => v.productCode === item.productCode)
        if (flag) {
          arr1.push(item)
        } else {
          const row = {
            productCode: item.productCode,
            productDesc: item.productName,
            modelCode: item.prodModelCode,
            modelName: item.prodModelName,
            categoryName: item.productCategoryName,
            categoryCode: item.productCategoryCode,
            seriesCode: item.saleSeriesCode,
            seriesName: item.saleSeriesName,
            productState: item.proState,
            pcontrolState: item.canBePurchase,
            productNumber: 1,
            placeOrderType: 'C',
            placeOrderDesc: ''
          }
          arr2.push(row)
        }
      })
      if (arr1.length > 0) {
        const msgArr = arr1.map(item => item.productCode)
        this.$message.warning(`编码为${msgArr.toString()}的产品已存在`)
      }
      this.proConfigTableData = [...this.proConfigTableData, ...arr2]
    },
    // 获取型号
    getModelData(data) {
      if (!this.proConfigTableData.length) {
        const dataArr = data.map(item => {
          const obj = {
            productCode: '',
            productDesc: '',
            modelCode: item.code,
            modelName: item.name,
            categoryName: '',
            categoryCode: '',
            seriesCode: item.saleSeriesCode,
            seriesName: item.saleSeriesName,
            productState: '',
            pcontrolState: '',
            productNumber: 1,
            placeOrderType: '',
            placeOrderDesc: ''
          }
          return obj
        })
        this.proConfigTableData = [...dataArr]
        return
      }
      const arr1 = []
      const arr2 = []
      data.forEach(item => {
        const flag = this.proConfigTableData.some(v => v.modelCode === item.modelCode)
        if (flag) {
          arr1.push(item)
        } else {
          const row = {
            productCode: '',
            productDesc: '',
            modelCode: item.code,
            modelName: item.name,
            categoryName: '',
            categoryCode: '',
            seriesCode: item.saleSeriesCode,
            seriesName: item.saleSeriesName,
            productState: '',
            pcontrolState: '',
            productNumber: 1,
            placeOrderType: '',
            placeOrderDesc: ''
          }
          arr2.push(row)
        }
      })
      if (arr1.length > 0) {
        const msgArr = arr1.map(item => item.modelCode)
        this.$message.warning(`编码为${msgArr.toString()}的型号已存在`)
      }
      this.proConfigTableData = [...this.proConfigTableData, ...arr2]
    },
    // 修改数量11
    handelBlur(row) {
      const num = Number(row.productNumber)
      if (isNaN(num) || num < 1 || (num % 1 !== 0)) {
        row.productNumber = 1
        this.$message.warning('请输入大于或等于1的整数')
      }
    },
    // 选择品类
    categoryChange(row) {
      row.categoryCode = row.category[0].code
      row.categoryName = row.category[0].name
    },
    // 删除
    delProduct() {
      if (this.selectedRows.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.proConfigTableData.length === this.selectedRows.length) {
          this.proConfigTableData = []
          return
        }
        let hasProduct = this.selectedRows.filter(item => item.productCode && item.productCode.length)
        let notProduct = this.selectedRows.filter(item => !item.productCode || !item.productCode.length)
        if (hasProduct.length > 0) {
          const tmpData = this.proConfigTableData.filter(row => {
            const index = hasProduct.findIndex(v => v.productCode === row.productCode)
            return index === -1
          })
          this.proConfigTableData = tmpData
          hasProduct = []
        }
        if (notProduct.length) {
          const tmpData = this.proConfigTableData.filter(row => {
            const index = notProduct.findIndex(v => v.modelCode === row.modelCode)
            return index === -1
          })
          this.proConfigTableData = tmpData
          notProduct = []
        }
        if (!notProduct.length && !hasProduct.length) {
          this.selectedRows = []
          this.$refs.refTable.clearSelection()
        }
      })
    },
    // 查看图纸详情
    toPicDetail(row) {
      this.rowId = row
      this.showPicDetail = true
    },
    // 返回配置详情
    backDetail() {
      this.showPicDetail = false
    },
    // 取消
    handleBack() {
      this.clearForm()
      this.$store.dispatch('views/goBack')
    },
    clearForm(done) {
      this.formData = {}
      this.$refs.rulesForm && this.$refs.rulesForm.clearValidate()
      done && done()
    },
    // 保存
    handleSave(schedule) {
      if (!this.proConfigTableData.length) {
        this.$message.warning('请添加产品配置清单')
        return
      }
      const flag = this.proConfigTableData.some(item => !item.categoryCode || !item.productNumber || !item.placeOrderType)
      if (flag) {
        this.$message.warning('请完善产品配置清单')
        return
      }
      this.proConfigTableData.forEach(item => {
        item.pControlState = item.pcontrolState
      })
      const picIds = this.formData.designPictureDtos.map(item => item.id)
      this.formData.picIds = picIds
      // this.formData.productConfigDetailDtos = this.proConfigTableData
      this.formData.productConfigOutpicDtos = []
      const prodObj = {}
      prodObj.configDetailDtos = this.proConfigTableData
      this.formData.productConfigOutpicDtos.push(prodObj)
      if (schedule === 'C') {
        this.formData.schedule = 'C'
      }
      this.loading = true
      this.loadingText = '系统处理中'
      saveProConfigEditData(this.formData).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.handleBack()
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    }
    // // 提交
    // clickNextStep() {
    //   if (!this.proConfigTableData.length) {
    //     this.$message.warning('请添加产品配置清单')
    //     return
    //   }
    //   const flag = this.proConfigTableData.some(item => !item.categoryCode || !item.productNumber || !item.placeOrderType)
    //   if (flag) {
    //     this.$message.warning('请完善产品配置清单')
    //     return
    //   }
    //   const picIds = this.formData.designPictureDtos.map(item => item.id)
    //   this.formData.picIds = picIds
    //   // this.formData.productConfigDetailDtos = this.proConfigTableData
    //   this.formData.productConfigOutpicDtos = []
    //   const prodObj = {}
    //   prodObj.configDetailDtos = this.proConfigTableData
    //   this.formData.productConfigOutpicDtos.push(prodObj)
    //   this.formData.schedule = 'C'
    //   this.loading = true
    //   this.loadingText = '系统处理中'
    //   saveProConfigEditData(this.formData).then(res => {
    //     if (res.success) {
    //       this.$message.success('操作成功')
    //       this.handleBack()
    //     }
    //     this.loading = false
    //   }).catch(() => {
    //     this.loading = false
    //   })
    // }
  }
}
</script>
<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/.el-breadcrumb__inner{
  color: $qup-color-primary;
}
</style>
